package com.iexbuy.ihg.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ViewPagerAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.AdObject;
import com.iexbuy.ihg.entity.LuckUserObject;
import com.iexbuy.ihg.entity.ShopCenter;
import com.iexbuy.ihg.entity.ThumbnailUrls;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.utils.UnitUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class YunGuoItemDetailFragment extends BaseFragment {
	
	private static YunGuoItemDetailFragment homeFragmentInstent;

	@ViewInject(R.id.pullToRefreshLayout)
	private PullToRefreshLayout pullToRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	@ViewInject(R.id.periodLayout)
	private LinearLayout periodLayout;
	@ViewInject(R.id.adItemList)
	private RelativeLayout adItemList;
	@ViewInject(R.id.itemName)
	private TextView itemName;
	@ViewInject(R.id.ItemText)
	private TextView ItemText;
	@ViewInject(R.id.itemValue)
	private TextView itemValue;
	@ViewInject(R.id.yunProgress)
	private ProgressBar yunProgress;
	@ViewInject(R.id.attendanceNo)
	private TextView attendanceNo;
	@ViewInject(R.id.totalRequireNo)
	private TextView totalRequireNo;
	@ViewInject(R.id.balenceNo)
	private TextView balenceNo;
	@ViewInject(R.id.selectPeriodBlock)
	private View selectPeriodBlock;
	@ViewInject(R.id.luckerImg)
	private ImageView luckerImg;
	@ViewInject(R.id.luckerName)
	private TextView luckerName;
	@ViewInject(R.id.luckerTotal)
	private TextView luckerTotal;
	@ViewInject(R.id.luckerNumber)
	private TextView luckerNumber;
	@ViewInject(R.id.luckerTime)
	private TextView luckerTime;
	@ViewInject(R.id.newPeriodTips)
	private TextView newPeriodTips;
	@ViewInject(R.id.oldPeriodLayout)
	private LinearLayout oldPeriodLayout;
	@ViewInject(R.id.submitYunguoLayout)
	private LinearLayout submitYunguoLayout;
	@ViewInject(R.id.progressLayout)
	private LinearLayout progressLayout;

	private BaseAdapter baseAdapter;

	private static YunItemListObject yunItemListObject;
	private static LuckUserObject luckUserObject;
	private static String areaCode;
	private int lastPeriod = 1;
	private int selectPeriod = 1;
	private static boolean isClosed=false;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_yunguo_item_detail, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.yun_guo_item_detail));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		pullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshDate();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
			}
		});
		pullToRefreshLayout.autoRefresh();
//		refreshDate();
	}

	@Override
	public void onResume() {
		super.onResume();
		if(isClosed){
			mBaseActivity.finish();
			isClosed=false;
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		areaCode=null;
	}

	//刷新整个页面数据
	private void refreshDate() {
		initYunGuoDetailData();
	}

	//获取商家详情
	private void initYunGuoDetailData() {
		if (yunItemListObject == null) return;

		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("itemId", yunItemListObject.getItemId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_LUCK_ITEM_BY_ID, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.LOADING);
					}

					@Override
					public void onCancelled() {
						pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.DONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
						String thumbnailUrl = yunItemListObject.getThumbnailUrl();
						yunItemListObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), YunItemListObject.class);
						yunItemListObject.setThumbnailUrl(thumbnailUrl);
						lastPeriod = Integer.valueOf(yunItemListObject.getPeriod());
						selectPeriod = lastPeriod;
						initPeriodView(lastPeriod);

						initShopDetailView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void initPeriodView(int totalPeriod) {
		periodLayout.removeAllViews();
		RelativeLayout periodView;
		for (int i = totalPeriod; i > 0; i --) {
			periodView = (RelativeLayout) mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.yunguo_period_single_text, null);
			((TextView)periodView.findViewById(R.id.itemName)).setText("第" + i + "期");
			periodLayout.addView(periodView);
			periodView.setTag(i);
			periodView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					int selectP = Integer.valueOf(view.getTag().toString());
					if (selectP == lastPeriod) {
						initYunGuoDetailData();
					} else {
						selectPeriod = selectP;
						updatePeriodViewStatus();
						getLuckItemByIdAndPeriod(selectP);
					}
				}
			});
		}
		updatePeriodViewStatus();
		initLuckUserView();
	}

	private void updatePeriodViewStatus() {
		//期数
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(UnitUtils.dip2px(mBaseActivity, 60), UnitUtils.dip2px(mBaseActivity, 2));
		lp.setMargins((lastPeriod - selectPeriod) * UnitUtils.dip2px(mBaseActivity, 60), UnitUtils.dip2px(mBaseActivity, 33), 0, 0);
		selectPeriodBlock.setLayoutParams(lp);
	}

	private void initShopDetailView() {

		
		//广告
//		CommUtil.initAdListData(mBaseActivity, "1", adItemList);
		initThumbnailUrls();
		
		//详情
		itemName.setText("第"+yunItemListObject.getPeriod()+"期" + yunItemListObject.getItemName());
		ItemText.setText(yunItemListObject.getItemName());
		itemValue.setText(yunItemListObject.getRequiredTotalNumber() + "元");
		attendanceNo.setText(yunItemListObject.getAttandanceNumber());
		totalRequireNo.setText(yunItemListObject.getRequiredTotalNumber());
		balenceNo.setText(String.valueOf(Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber())));
		yunProgress.setProgress(new BigDecimal(yunItemListObject.getAttandanceNumber()).divide(new BigDecimal(yunItemListObject.getRequiredTotalNumber()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).intValue());
	}

	private void initThumbnailUrls() {
		List<String> urls = new ArrayList<String>();

		for (final ThumbnailUrls url : yunItemListObject.getThumbnailUrls()) {
			urls.add(url.getUrl());

		}

		CommUtil.initScrollViewPages(mBaseActivity, adItemList, urls, null);

	}

	/**
	 * 获取往期资料
	 * @param period
	 */
	private void getLuckItemByIdAndPeriod(int period) {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("itemId", yunItemListObject.getItemId());
		paramMap.put("period", String.valueOf(period));
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_LUCK_ITEM_BY_ID_AND_PEROID, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						luckUserObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), LuckUserObject.class);
						Log.d("aa",luckUserObject+"");
						initLuckUserView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});

	}

	private void initLuckUserView(){

		if (luckUserObject != null) {
			luckerName.setText(StringUtil.hideMobileNo(luckUserObject.getLuckUerName()));
			luckerTotal.setText(luckUserObject.getYunGouTimes());
			luckerNumber.setText(luckUserObject.getLuckNo());
			luckerTime.setText(luckUserObject.getTime());
			newPeriodTips.setText("本期已结束，第" + lastPeriod + "期正在进行中");
		}

		if (selectPeriod == lastPeriod) {
			progressLayout.setVisibility(View.VISIBLE);
			oldPeriodLayout.setVisibility(View.GONE);
			submitYunguoLayout.setVisibility(View.VISIBLE);
		} else {
			progressLayout.setVisibility(View.GONE);
			oldPeriodLayout.setVisibility(View.VISIBLE);
			submitYunguoLayout.setVisibility(View.GONE);
		}
	}

	/**
	 * 立即参与
	 * @param view
	 */
	//点击事件响应
	@OnClick(R.id.submitYunguoBtn)
	public void onSubmitYunguoBtnClick(View view) {
		if (yunItemListObject == null) {
			ToastUtils.toast(mBaseActivity, "产品信息没加载完成或已过期，请下拉刷新最新产品信息。");
			return;
		}
		if(areaCode!=null){
			YunGuoOrderConfirmFragment.setAreaCode(areaCode);

		}
		YunGuoOrderConfirmFragment.setYunItemListObject(yunItemListObject);
		CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoOrderConfirmFragment.class);
	}

	/**
	 * 所有0购记录
	 * @param view
	 */
	@OnClick(R.id.yunguoRecords)
	public void onYunguoRecordsClick(View view) {
		YunGuoAttenceRecordsFragment.setYunItemListObject(yunItemListObject);
		CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoAttenceRecordsFragment.class);
	}

	/**
	 * 图文介绍
	 * @param view
	 */
	@OnClick(R.id.ricText)
	public void onRicTextClick(View view) {
		YunGuoDescFragment.setYunItemListObject(yunItemListObject);
		CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoDescFragment.class);
	}

	@OnClick(R.id.checkResultBtn)
	public void checkResultBtnClick(View view) {
		YunGuoCalculationRecordsFragment.setYunItemListObject(yunItemListObject);
		YunGuoCalculationRecordsFragment.setPeriod(selectPeriod);
		CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoCalculationRecordsFragment.class);
	}

	@OnClick(R.id.attendanceBtn)
	public void attendanceBtnClick(View view) {
		initYunGuoDetailData();
	}

	public static void setYunItemListObject(YunItemListObject yunItemListObject) {
		YunGuoItemDetailFragment.yunItemListObject = yunItemListObject;
	}
	public static void setAreaCode(String areaCode) {
		YunGuoItemDetailFragment.areaCode = areaCode;
	}
	public static void setIsClosed(boolean isClosed) {
		YunGuoItemDetailFragment.isClosed = isClosed;
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static YunGuoItemDetailFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
